package com.seeyon.apps.commonExt.util;

import com.seeyon.cap4.form.exception.FormException;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.util.json.JSONUtil;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @description:
 * @author: huangjin
 * @time: 2025/6/14 10:14
 */
public class CommonRestUtil {

    private static final Logger log = LoggerFactory.getLogger(CommonRestUtil.class);

    public static ResponseEntity<String> call(boolean valid, APIBaseOperation base, HttpMethod httpMethod, Map<String, String> httpHeaders, Object params, Object...urlParams) {
        ResponseEntity<String> exchange = null;
        try {
            HttpHeaders httpHeaders1 = new HttpHeaders();
            if (httpMethod == HttpMethod.POST) {
                httpHeaders1.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
            }
            if (MapUtil.isNotEmpty(httpHeaders)) {
                httpHeaders1.setAll(httpHeaders);
            }
            RestTemplate restTemplate = (RestTemplate) AppContext.getBean("restTemplateFormat");
            Assert.notNull(restTemplate, "restTemplate为空");
            log.info("【{}】url参数【{}】请求体参数【{}】", base.desc(), JSONUtil.toJSONString(urlParams), JSONUtil.toJSONString(params));
            exchange = restTemplate.exchange(base.url(), httpMethod, new HttpEntity<>(params, httpHeaders1), String.class, urlParams);
            log.info("【{}】返回参数【{}】", base.desc(), exchange.getBody());
            Assert.isTrue(exchange.getStatusCode() == HttpStatus.OK, "【{}】http状态码错误", base.desc());
            if (valid) {
                base.success(exchange.getBody());
            }
        } catch (RestClientException e) {
            log.error("【{}】服务异常", base.desc(), e);
            throw new FormException(String.format("【%s】服务异常", base.desc()), e);
        }
        return exchange;
    }


    public static ResponseEntity<String> get(APIBaseOperation base, Map<String, String> httpHeaders, Object...urlParams) {
        return call(false, base, HttpMethod.GET, httpHeaders, null, urlParams);
    }

    public static ResponseEntity<String> post(APIBaseOperation base, Map<String, String> httpHeaders, Object params, Object...urlParams) {
        return call( false, base, HttpMethod.POST, httpHeaders, params, urlParams);
    }

    public static ResponseEntity<String> postValid(APIBaseOperation base, Map<String, String> httpHeaders, Object params, Object...urlParams) {
        return call( true, base, HttpMethod.POST, httpHeaders, params, urlParams);
    }
}
